<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'wms:wh:pos:whWarePosjust:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #whWarePosjustRdsList>
        <a-button
          v-if="!disabled"
          class="mb-2"
          @click="handleWhWarePosjustRdsAdd"
          v-auth="'wms:wh:pos:whWarePosjust:edit'"
        >
          <Icon icon="ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
        <BasicTable
          @register="registerWhWarePosjustRdsTable"
          @row-click="handleWhWarePosjustRdsRowClick"
        />
      </template>
    </BasicForm>
    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        bpmEntityKey="id"
        formKey="flow_wh_ware_posJust"
        completeText="提交"
        :completeModal="true"
        :loading="loadingRef"
        :auth="'wms:wh:pos:whWarePosjust:edit'"
        @validate="handleValidate"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
    <ListSelect
      ref="listSelectRef"
      :selectList="selectListRef"
      selectType="basInvSelect"
      :queryParams="queryParams"
      :checkbox="true"
      @select="handleSelect"
      v-show="false"
    />
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsWmsWhPosWhWarePosjustForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import {
    WhWarePosjust,
    whWarePosjustSave,
    whWarePosjustForm,
  } from '/@/api/wms/wh/pos/whWarePosjust';
  import { companyTreeData } from '/@/api/sys/company';
  import { basWarehouseTreeData } from '/@/api/bas/house/basWarehouse';
  import { basPositionTreeData } from '/@/api/bas/pos/basPosition';
  import { BpmButton } from '/@/components/Bpm';
  import { ListSelect } from '/@/components/ListSelect';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('wms.wh.pos.whWarePosjust');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<WhWarePosjust>({} as WhWarePosjust);
  const loadingRef = ref(false);
  const listSelectRef = ref<any>(null);
  const selectListRef = ref<any>([]);
  const whCode = ref<any>('');
  const disabled = ref<any>(false);
  const queryParams = ref({});

  const getTitle = computed(() => ({
    icon: meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增货位调整单') : t('编辑货位调整单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('调整单号'),
      field: 'code',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('单据日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
        valueFormat: 'YYYY-MM-DD',
      },
      required: true,
      dynamicDisabled: true,
    },
    // {
    //   label: t('公司'),
    //   field: 'companyCode',
    //   fieldLabel: 'company.companyName',
    //   component: 'TreeSelect',
    //   componentProps: {
    //     api: companyTreeData,
    //     allowClear: true,
    //     onChange: async (e) => {
    //       queryParams.value = {
    //         companyCode: e,
    //       };
    //       let arr = await whWarePosjustRdsTable.getDataSource();
    //       let arrNew = [...arr];
    //       arrNew.forEach(async (item, index) => {
    //         await whWarePosjustRdsTable.deleteTableDataRecord(item);
    //       });
    //     },
    //   },
    //   required: true,
    // },
    {
      label: t('业务类型'),
      field: 'busType',
      component: 'Select',
      componentProps: {
        dictType: 'wh_poJust_bus_type',
        allowClear: true,
        disabled: computed(() => disabled.value),
      },
      required: true,
    },
    {
      label: t('仓库'),
      field: 'whcode',
      fieldLabel: 'basWare.cwhname',
      component: 'TreeSelect',
      componentProps: {
        api: basWarehouseTreeData,
        allowClear: true,
        onChange: async (value) => {
          whCode.value = value || '-1';
          setWhWarePosjustRdsColumns();
          let arr = await whWarePosjustRdsTable.getDataSource();
          let arrNew = [...arr];
          arrNew.forEach(async (item, index) => {
            let editValueRefs = item.editValueRefs;
            editValueRefs.beforePos = '';
            editValueRefs.afterPos = '';
            await whWarePosjustRdsTable.updateTableDataRecord(item.id, {
              ...item,
              beforePos: '',
              afterPos: '',
              editValueRefs,
            });
          });
        },
      },
      required: true,
    },
    {
      label: t('制单时间'),
      field: 'createDate',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    {
      label: t('制单人'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      dynamicDisabled: true,
    },
    // {
    //   label: t('修改人名称'),
    //   field: 'updateByName',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 64,
    //   },
    //   dynamicDisabled: true,
    // },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        disabled: computed(() => disabled.value),
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('货位调整明细'),
      field: 'whWarePosjustRdsList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'whWarePosjustRdsList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate, getFieldsValue }] =
    useForm({
      labelWidth: 120,
      schemas: inputFormSchemas,
      baseColProps: { lg: 12, md: 24 },
    });

  const [registerWhWarePosjustRdsTable, whWarePosjustRdsTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleWhWarePosjustRdsDelete.bind(this, record),
          },
          auth: 'wms:wh:pos:whWarePosjust:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setWhWarePosjustRdsColumns(_res: Recordable) {
    whWarePosjustRdsTable.setColumns([
      // {
      //   title: t('公司'),
      //   dataIndex: 'parent.company.companyName',
      //   width: 150,
      //   align: 'left',
      //   editRow: false,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: true,
      // },
      {
        title: t('产品编码'),
        dataIndex: 'basInv.viewCode',
        width: 110,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
      },
      {
        title: t('产品编码'),
        dataIndex: 'invCode',
        width: 140,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: true,
        ifShow: false,
      },
      {
        title: t('产品名称'),
        dataIndex: 'basInv.invName',
        width: 160,
        align: 'left',
        editRow: false,
        editComponent: 'Input',
        editComponentProps: {},
        editRule: true,
      },
      {
        title: t('数量'),
        dataIndex: 'iqty',
        width: 80,
        align: 'center',
        editRow: true,
        // editRow: computed(() => !disabled.value),
        editComponent: 'InputNumber',
        editComponentProps: ({ record: record1 }) => {
          return {
            min: 1,
            disabled: disabled.value,
            // onChange: (value, label) => {
            //   let iqty = value;
            //   if (record.value.bred == 0) {
            //     if (value > 0) {
            //       iqty = -value;
            //     }
            //   } else {
            //     if (value < 0) {
            //       iqty = -value;
            //     }
            //   }
            //   rds01Table.updateTableDataRecord(record1.id, {
            //     ...record1,
            //     iqty,
            //   });
            // },
          };
        },
        editRule: (value, _record) => {
          return new Promise((resolve, reject) => {
            if (value == 0) return reject('数量不能为0');
            if (!value || value == '') return reject('请输入数量');
            return resolve(); // 验证成功
          });
        },
      },
      {
        title: t('货位调整前'),
        dataIndex: 'beforePos',
        dataLabel: 'beforePosition.posName',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'TreeSelect',
        editComponentProps: {
          disabled: disabled.value,
          api: basPositionTreeData,
          params: { whcode: whCode.value },
          allowClear: true,
          canSelectParent: false,
        },
        editRule: true,
      },
      {
        title: t('货位调整后'),
        dataIndex: 'afterPos',
        dataLabel: 'afterPosition.posName',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'TreeSelect',
        editComponentProps: {
          disabled: disabled.value,
          api: basPositionTreeData,
          params: { whcode: whCode.value },
          allowClear: true,
          canSelectParent: false,
        },
        editRule: true,
      },
      // {
      //   title: t('形象刊'),
      //   dataIndex: 'freeVO.cfree1',
      //   width: 100,
      //   align: 'left',
      //   // editRow: true,
      //   editRow: computed(() => !disabled.value),
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 100,
      //   },
      //   editRule: false,
      // },
      {
        title: t('自由项2'),
        dataIndex: 'freeVO.cfree2',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('自由项3'),
        dataIndex: 'freeVO.cfree3',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('来源单据'),
        dataIndex: 'sourceId',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        // ifShow: false,
      },
      {
        title: t('来源明细ID'),
        dataIndex: 'sourceDid',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('备注信息'),
        dataIndex: 'remarks',
        width: 130,
        align: 'left',
        // editRow: true,
        editRow: computed(() => !disabled.value),
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 500,
        },
        editRule: false,
      },
    ]);
  }

  async function setWhWarePosjustRdsTableData(_res: Recordable) {
    await setWhWarePosjustRdsColumns();
    whWarePosjustRdsTable.setTableData(record.value.whWarePosjustRdsList || []);
  }

  function handleWhWarePosjustRdsRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleWhWarePosjustRdsAdd() {
    // if (!getFieldsValue().companyCode) {
    //   showMessage('请先选择公司！');
    //   return;
    // }
    selectListRef.value = [];
    listSelectRef.value.openSelectModal();
    // whWarePosjustRdsTable.insertTableDataRecord({
    //   id: new Date().getTime(),
    //   isNewRecord: true,
    //   editable: true,
    // });
  }

  function handleSelect(selectData) {
    selectData.forEach((item, index) => {
      whWarePosjustRdsTable.insertTableDataRecord({
        id: new Date().getTime() + index,
        isNewRecord: true,
        editable: true,
        invCode: item.invCode,
        companyCode: item.companyCode,
        basInv: {
          viewCode: item.viewCode,
          invName: item.invName,
          funitname: item.funitname,
        },
        // cfree2: item.weight,
        // parent: {
        //   company: {
        //     companyName: item.company.companyName,
        //   },
        // },
      });
    });
  }

  function handleWhWarePosjustRdsDelete(record: Recordable) {
    whWarePosjustRdsTable.deleteTableDataRecord(record);
  }

  async function getWhWarePosjustRdsList() {
    let whWarePosjustRdsListValid = true;
    let whWarePosjustRdsList: Recordable[] = [];
    for (const record of whWarePosjustRdsTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        whWarePosjustRdsListValid = false;
      }
      whWarePosjustRdsList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of whWarePosjustRdsTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      whWarePosjustRdsList.push({
        ...record,
        status: '1',
      });
    }
    if (!whWarePosjustRdsListValid) {
      throw { errorFields: [{ name: ['whWarePosjustRdsList'] }] };
    }
    return whWarePosjustRdsList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await whWarePosjustForm(data);
    record.value = (res.whWarePosjust || {}) as WhWarePosjust;
    record.value.__t = new Date().getTime();
    whCode.value = record.value.whcode || '-1';
    queryParams.value = {
      companyCode: record.value.companyCode,
    };
    setFieldsValue(record.value);
    if (
      !record.value.status ||
      record.value.status == '9' ||
      record.value.status == '5' ||
      record.value.status == '6'
    ) {
      disabled.value = false;
    } else {
      disabled.value = true;
    }
    whWarePosjustRdsTable.setProps({
      actionColumn: {
        ifShow: !disabled.value,
        width: 60,
        actions: (record: Recordable) => [
          {
            icon: 'ant-design:delete-outlined',
            color: 'error',
            popConfirm: {
              title: '是否确认删除',
              confirm: handleWhWarePosjustRdsDelete.bind(this, record),
            },
            auth: 'wms:wh:pos:whWarePosjust:edit',
          },
        ],
      },
    });
    await setWhWarePosjustRdsTableData(res);
    updateSchema([
      {
        field: 'code',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
      {
        field: 'whcode',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
      {
        field: 'companyCode',
        componentProps: {
          disabled: !record.value.isNewRecord,
        },
      },
    ]);
    setDrawerProps({ loading: false });
  });

  async function handleValidate(_event: any, formData: any) {
    try {
      const data = await validate();
      formData(true, data); // 将表单数据传递给 BpmButton
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    }
  }

  async function handleSubmit(event: any) {
    try {
      loadingRef.value = true;
      const data = await validate(); // 接受 BpmButton 传递过来的表单数据
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm); // 流程信息
      data.status = record.value.status; // 提交状态
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        code: record.value.code,
      };
      data.whWarePosjustRdsList = await getWhWarePosjustRdsList();
      // console.log('submit', params, data, record);
      const res = await whWarePosjustSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
